package com.qqletter.utils;

import java.io.IOException;

import com.qqletter.common.Constants;
import com.qqletter.request.BaseRequest;
import com.qqletter.response.BaseResponse;

/**
 * @author Devin.Hu
 * @date 2011-8-12
 * @version V1.0
 * @description http请求处理类
 */
public class DefaultClient {

	/**请求URL**/
	private String serverUrl;
	/**是否签名**/
	private boolean isCheckSign = false;
	/**解析方式**/
	private String format = Constants.FORMAT_JSON;

	/**
	 * 构造方法
	 * @param serverUrl
	 */
	public DefaultClient(String serverUrl) {
		this.serverUrl = serverUrl;
	}

	/**
	 * 构造方法
	 * @param serverUrl
	 * @param isCheckSign
	 */
	public DefaultClient(String serverUrl, boolean isCheckSign) {
		this(serverUrl);
		this.isCheckSign = isCheckSign;
	}

	/**
	 * 构造方法
	 * @param serverUrl
	 * @param isCheckSign
	 * @param format
	 */
	public DefaultClient(String serverUrl, boolean isCheckSign, String format) {
		this(serverUrl, isCheckSign);
		this.format = format;
	}

	/**
	 * 发送请求方法
	 * 
	 * @param <T>
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public <T extends BaseResponse> T execute(BaseRequest<T> req) throws Exception {

		T responseT = null;

		ParameterUtils paramUtils = new ParameterUtils();
		paramUtils.addStringParam(Constants.SYS_PARAM_FORMAT, format);
		req.getTextParams(paramUtils);

		if (isCheckSign) {
			//paramUtils.makeSign(req.getApiMethodName(), paramUtils.getParamsMap(), Constants.SKEY, Constants.CHARSET_UTF8);
		}

		String rsp = WebUtils.doGet(serverUrl, paramUtils.getParamsMap());
		System.out.println(" -------------------------> response result : " + rsp);

		if (format.equals(Constants.FORMAT_JSON)) {
			ObjectJsonParser<T> jsonParser = new ObjectJsonParser<T>(req.getResponseClass());
			responseT = jsonParser.parse(rsp);
		}

		return responseT;
	}
	
	/**
	 *  发送请求方法
	 *  
	 * @return
	 * @throws IOException
	 */
	public String execute() throws IOException{
		String rsp = null;
		if(!StringUtils.isEmpty(serverUrl)){
			rsp = WebUtils.doGet(serverUrl);
		}
		System.out.println(" -------------------------> response result : " + rsp);
		return rsp;
	}
	
}
